package ua.pp.bizon.yandex.jmx;

/*
 * Copyright (c) 2004 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */

import ua.pp.bizon.yandex.api.IJobExecutor;
import ua.pp.bizon.yandex.api.ObjectLookup;
import ua.pp.bizon.yandex.api.Query;
import ua.pp.bizon.yandex.api.QueryMBean;
import ua.pp.bizon.yandex.uploader.QueryClient;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;

public class Service implements IJMXService {

	public static final String OBJECT_NAME = "ua.pp.bizon.yandex.api:type=Uploader";
	public static final Log log = LogFactory.getLog(Service.class);

	protected MBeanServerConnection startService() {
		log.debug("service starting");
		MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
		queryMBean = new Query();
		try {
			ObjectName name = new ObjectName(OBJECT_NAME);
			mbs.registerMBean(queryMBean, name);
			queryMBean.addNotificationListener(ObjectLookup.lookup(IJobExecutor.class).listener(), null, null);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
		log.debug("service " + mbs.toString() + " has being started");
		return mbs;
	}

	static MBeanServerConnection findService(String serviceName, String objectName) {
		log.debug("lookup: " + serviceName);
		Map<String, VirtualMachine> result = new HashMap<String, VirtualMachine>();
		List<VirtualMachineDescriptor> list = (List<VirtualMachineDescriptor>) VirtualMachine.list();
		try {
			for (VirtualMachineDescriptor vmd : list) {
				String desc = vmd.toString();
				log.trace("found: " + desc);
				VirtualMachine attach = VirtualMachine.attach(vmd);
				if (desc.contains(serviceName)) {
					result.put(desc, attach);
				}

			}
			for (VirtualMachine vm : result.values()) {
				if (vm != null) {
					Properties props = vm.getAgentProperties();
					String connectorAddress = props.getProperty(Service.CONNECTOR_ADDRESS_PROPERTY);
					if (connectorAddress == null) {
						props = vm.getSystemProperties();
						String home = props.getProperty("java.home");
						String agent = home + File.separator + "lib" + File.separator + "management-agent.jar";
						vm.loadAgent(agent);
						props = vm.getAgentProperties();
						connectorAddress = props.getProperty(Service.CONNECTOR_ADDRESS_PROPERTY);
					}
					JMXServiceURL url = new JMXServiceURL(connectorAddress);
					JMXConnector con = JMXConnectorFactory.connect(url);
					MBeanServerConnection mBeanServerConnection = con.getMBeanServerConnection();
					if (mBeanServerConnection.isRegistered(new ObjectName(objectName))) {
						return mBeanServerConnection;
					}
				}
			}
		} catch (Exception e) {
			log.fatal(e.getMessage(), e);
		}
		return null;
	}

	static final String CONNECTOR_ADDRESS_PROPERTY = "com.sun.management.jmxremote.localConnectorAddress";

	public boolean init(boolean asService, boolean connect) {
		if (!asService) {
			startLocally();
			return true;
		} else {
			try {
				MBeanServerConnection connection = findService("", Service.OBJECT_NAME);
				if (connection == null) {
					if (!connect) {
						connection = startService();
						log.debug("service started locally");
					}
				} else {
					queryMBean = new QueryClient(connection);
					log.debug("service started remotely");
				}
				return true;
			} catch (MalformedObjectNameException e) {
				log.error(e);
			} catch (NoClassDefFoundError e) {
				log.warn("service not started ant not found! please add  %JAVA_HOME%\\lib\\tools.jar to classpath!!");
				// startLocally();
			}
		}
		return false;
	}

	private void startLocally() {
		queryMBean = new Query();
		((Query) queryMBean).addNotificationListener(ObjectLookup.lookup(IJobExecutor.class).listener(), null, null);
		log.debug("queryMBean set up locally");
	}

	private QueryMBean queryMBean;

	@Override
	public QueryMBean getQuery() {
		return queryMBean;
	}
}
